package com.kaifamiao.wendao.service;

import com.kaifamiao.wendao.dao.CustomerDao;
import com.kaifamiao.wendao.dao.ExplainDao;
import com.kaifamiao.wendao.dao.TopicDao;
import com.kaifamiao.wendao.entity.Customer;
import com.kaifamiao.wendao.entity.Explain;
import com.kaifamiao.wendao.entity.Topic;
import com.kaifamiao.wendao.utils.SnowflakeIdGenerator;

import java.time.LocalDateTime;
import java.util.List;

public class TopicService {

    private TopicDao topicDao = new TopicDao();
    private ExplainDao explainDao=new ExplainDao();
    private CustomerDao customerDao=new CustomerDao();

    public Boolean save(Topic topic){
        topic.setId(SnowflakeIdGenerator.getInstance().generate());
        topic.setPublishTime(LocalDateTime.now());
        topic.setPriority(1);
        return topicDao.save(topic);
    }

    public List<Topic> loadAll(){
        return topicDao.findAll();
    }

    public List<Topic> loadAll(Long cid){
        return topicDao.findAll(cid);
    }

    public boolean remove(Long id){
        return topicDao.remove(id);
    }

    public List<Topic> loadAll(String word){
        return topicDao.findAll(word);
    }

    public Topic load(Long id){
        // 根据 topic id 获取单个Topic实例
        Topic t = topicDao.find(id);

        // 从Topic实例中获得Customer实例(其中只有一个 customer id 值)
        Customer c = t.getAuthor();
        // 根据 customer id 查询用户信息
        c = customerDao.find(c.getId());
        // 将查询后得到的Customer实例重新设置到Topic实例的author属性
        t.setAuthor(c);

        // 根据 topic id 查询所有的"解答"(explain)
        List<Explain> explains = explainDao.findByTopicId(id);
        for(Explain e : explains){
            Customer a = e.getAuthor();
            a = customerDao.find(a.getId());
            e.setAuthor(a);
        }
        // 为当前话题设置"解答"列表
        t.setExplains(explains);

        return t;
    }

    public boolean update(Topic topic){
        return topicDao.update(topic);
    }

    public List<Topic> find_re(String tag){
      return topicDao.findAll_Order(tag);
    }
}
